package site.wetsion.employ.server.controller;

import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.List;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import site.wetsion.employ.server.pojo.Company;
import site.wetsion.employ.server.pojo.CompanyDetail;
import site.wetsion.employ.server.pojo.CompanyProduct;
import site.wetsion.employ.server.pojo.Domain;
import site.wetsion.employ.server.pojo.EnterpriseUser;
import site.wetsion.employ.server.pojo.Job;
import site.wetsion.employ.server.pojo.JobRequestDetail;
import site.wetsion.employ.server.pojo.User;
import site.wetsion.employ.server.service.CompanyService;
import site.wetsion.employ.server.service.EnterpriseUserService;
import site.wetsion.employ.server.service.JobService;
import site.wetsion.employ.server.service.UserService;
import site.wetsion.employ.server.util.Page;
import site.wetsion.employ.server.util.Result;
import site.wetsion.employ.server.util.SendCode;
import site.wetsion.employ.server.vo.CompanyProductVo;
import site.wetsion.employ.server.vo.EnterpriseUserVo;
import site.wetsion.employ.server.vo.JobVo;

@Controller
public class EnterpriseUserController {

	private final static Logger log = LoggerFactory.getLogger(EnterpriseUserController.class);

	
	@Autowired
	private EnterpriseUserService enterpriseUserService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private UserService userService;
	@Autowired
	private JobService jobService;

	@GetMapping("user/enterprise/mycompany")
	public String mycompany(HttpSession session){
		User user = (User) session.getAttribute("curr_user");
		if(user==null){
			return "redirect:/login";
		}
		EnterpriseUser euser = enterpriseUserService.getEnterpriseUserByUid(user.getId());
		if(euser == null){
			return "user/enterprise/bind_company";
		}else{
			if(euser.getStatus() == 0){
				return "user/enterprise/bind_submited";
			}
			return "redirect:/company/detail/"+euser.getEnterprise_company_id();
		}
	}
	
	/** 企业用户绑定公司*/
	@PostMapping("user/enterprise/bindcompany")
	public String bindcompany(String checkfile, HttpSession session, 
			String company_name, BigInteger company_id){
		User user= (User) session.getAttribute("curr_user");
		if(user==null){
			return "redirect:/login";
		}
		EnterpriseUser enterpriseUser = new EnterpriseUser();
		enterpriseUser.setEnterprise_checkfile(checkfile);
		enterpriseUser.setEnterprise_company_id(company_id);
		enterpriseUser.setEnterprise_user_id(user.getId());
		boolean rs = enterpriseUserService.bindcompany(enterpriseUser);
		if(rs){
			return "user/enterprise/bind_submited";
		}
		return "redirect:/user/enterprise/mycompany";
	}
	
	@GetMapping("user/enterprise/addcompany")
	public String addcompany(Model model){
		List<Domain> domainList = companyService.showAllDomain();
		model.addAttribute("domainList", domainList);
		return "user/enterprise/addcompany_step1";
	}
	
	/** 用户添加公司，提交审核  */
	@ResponseBody
	@PostMapping("user/enterprise/addnewcompany")
	public Result addcompany(CompanyProductVo companyProductVo, HttpSession session){
		User user =(User) session.getAttribute("curr_user");
		if(user==null){
			return new Result(400, "未登录");
		}
		System.out.println(companyProductVo.getCompany().toString());
		System.out.println(companyProductVo.getProduct().toString());
		companyProductVo.getCompany().setCompany_creater(user.getId());
		boolean rs = enterpriseUserService.userCommitCompany(companyProductVo.getCompany(),
				companyProductVo.getProduct(), companyProductVo.getCompanyDetail());
		if(rs){
			return new Result(200, "添加成功");
		}
		return new Result(500, "添加失败");
//		return "redirect:/admin/addcompany";
	}
	
	
	/**----------------------  管理员对企业用户的相关操作  ----------------------------*/
	/** 根据id ajax查询企业用户表*/
	@ResponseBody
	@GetMapping("admin/queryEnterpriseUser")
	public EnterpriseUserVo queryEnterpriseUserById(BigInteger id){
		EnterpriseUser enterpriseUser = enterpriseUserService.getEnterpriseUserByid(id);
		Company company = companyService.getCompanyById(enterpriseUser.getEnterprise_company_id());
		User user = userService.getUserById(enterpriseUser.getEnterprise_user_id());
		EnterpriseUserVo vo = new EnterpriseUserVo();
		vo.setCompany(company);
		vo.setEnterpriseUser(enterpriseUser);
		vo.setUser(user);
		return vo;
	}
	
	/** 审核企业用户*/
	@ResponseBody
	@PostMapping("admin/checkEnterpriseUser")
	public Result checkEnterpriseUser(BigInteger id, BigInteger userid,
			int status, String sugestion){
		User user = userService.getUserById(userid);
		String title = "";
		String content = "";
		if(status == 0){
			boolean rs = enterpriseUserService.modifyEnterpriseUserStatus(id, -1);
			if(rs){
				title = "公司绑定审核不通过";
				content = sugestion;
				try {
					SendCode.sendEmail(title, content, user.getEmail());
				} catch (Exception e) {
					log.error("发送邮件失败", e);
					return new Result(202, "审核成功，发送邮件失败，请管理员手动发送");
				}
				return new Result(200, "审核成功");
			}
		}else{
			boolean rs = enterpriseUserService.modifyEnterpriseUserStatus(id, 1);
			if(rs){
				title = "公司绑定审核通过";
				content = "公司绑定审核已通过！";
				try {
					SendCode.sendEmail(title, content, user.getEmail());
				} catch (Exception e) {
					log.error("发送邮件失败", e);
					return new Result(202, "审核成功，发送邮件失败，请管理员手动发送");
				}
				return new Result(200, "审核成功");
			}
		}
		return new Result(400, "审核失败！");
	}
	
	/** 获取未审核用户总数*/
	@ResponseBody
	@GetMapping("admin/getUncheckEnterpriseUserCount")
	public int getUncheckEnterpriseUserCount(){
		return enterpriseUserService.getUncheckEnterpriseUserCount();
	}
	
	/** 分页获取未审核用户*/
	@GetMapping("admin/enterprise_user_check/{pageNum}")
	public String enterprise_user_check(@PathVariable int pageNum, Model model){
		Page page = new Page(pageNum, 15);
		List<EnterpriseUser> enterpriseUserList = enterpriseUserService.getUncheckEnterpriseUserList(page);
		int count = enterpriseUserService.getUncheckEnterpriseUserCount();
		page.setTotalRecord(count);
		model.addAttribute("enterpriseUserList", enterpriseUserList);
		model.addAttribute("page", page);
		return "admin/enterprise_user_check";
	}
	
	
	/**   企业*/
	
	/** 根据id ajax查询未审核企业*/
	@ResponseBody
	@GetMapping("admin/queryEnterpriseUncheck")
	public CompanyProductVo queryEnterpriseUncheckById(BigInteger id){
		Company company = enterpriseUserService.getCompanyUncheckById(id);
		CompanyDetail detail = enterpriseUserService.getCompanyDetailUncheckById(
				company.getCompany_detail());
		CompanyProduct product = enterpriseUserService.getCompanyProductUncheckByCompanyId(id);
		CompanyProductVo vo = new CompanyProductVo();
		vo.setCompany(company);
		vo.setCompanyDetail(detail);
		vo.setProduct(product);
		return vo;
	}
	
	/** 分页获取未审核企业列表*/
	@GetMapping("admin/enterprise_check/{pageNum}")
	public String enterprise_check(@PathVariable int pageNum, Model model){
		Page page = new Page(pageNum, 10);
		List<Company> companyList = enterpriseUserService.getAllUncheckCompanyByPage(page);
		int count = enterpriseUserService.getUncheckCompanyCount();
		page.setTotalRecord(count);
		model.addAttribute("companyList", companyList);
		model.addAttribute("page", page);
		List<Domain> domainList = companyService.showAllDomain();
		model.addAttribute("domainList", domainList);
		return "admin/enterprise_check";
	}
	
	/** 获取未审核企业总数*/
	@ResponseBody
	@GetMapping("admin/getUncheckEnterpriseCount")
	public int getUncheckEnterpriseCount(){
		return enterpriseUserService.getUncheckCompanyCount();
	}
	
	/** 审核企业*/
	@ResponseBody
	@PostMapping("admin/checkEnterprise")
	public Result checkEnterprise(
			BigInteger id, BigInteger userid,
			BigInteger productid, BigInteger detailid,
			int status, String sugestion){
		User user = userService.getUserById(userid);
		String title = "";
		String content = "";
		if(status == 0){
			boolean rs = enterpriseUserService.deleteEnterpriseUncheck(id);
			if(rs){
				title = "公司审核不通过";
				content = sugestion;
				try {
					SendCode.sendEmail(title, content, user.getEmail());
				} catch (Exception e) {
					log.error("发送邮件失败", e);
					return new Result(202, "审核成功，发送邮件失败，请管理员手动发送");
				}
				return new Result(200, "审核成功");
			}
		}else{
			Company company = enterpriseUserService.getCompanyUncheckById(id);
			CompanyDetail detail = enterpriseUserService.getCompanyDetailUncheckById(detailid);
			CompanyProduct product = enterpriseUserService.getCompanyProductUncheckByCompanyId(id);
			boolean rsa = enterpriseUserService.addNewCompanyFromUncheck(company,product,detail);
			boolean rsd = enterpriseUserService.deleteEnterpriseUncheck(id);
			boolean rs = enterpriseUserService.deleteCompanyDetailUncheck(detailid);
			boolean rsp = enterpriseUserService.deleteCompanyPorductUncheck(productid);
			if(rsa && rs && rsd && rsp){
				title = "公司审核通过";
				content = "公司审核已通过！";
				try {
					SendCode.sendEmail(title, content, user.getEmail());
				} catch (Exception e) {
					log.error("发送邮件失败", e);
					return new Result(202, "审核成功，发送邮件失败，请管理员手动发送");
				}
				return new Result(200, "审核成功");
			}
		}
		return new Result(400, "审核失败！");
	}
	
	/**----------------------  end  -----------------------------*/
	
	@GetMapping("user/enterprise/myjob/{pageNum}")
	public String myjob(@PathVariable int pageNum, 
			HttpSession session, Model model){
		User user = (User) session.getAttribute("curr_user");
		if(user==null){
			return "redirect:/login";
		}
		EnterpriseUser euser = enterpriseUserService.getEnterpriseUserByUid(user.getId());
		if(euser == null){
			return "user/enterprise/bind_company";
		}else{
			if(euser.getStatus() == 0){
				return "user/enterprise/bind_submited";
			}
			Page page = new Page(pageNum, 15);
			List<Job> validJobList = jobService.getValidJobListByUid(user.getId(), page);
			int count = jobService.getCountOfValidJobByCreaterId(user.getId());
			page.setTotalRecord(count);
			model.addAttribute("validJobList", validJobList);
			model.addAttribute("page", page);
			return "user/enterprise/valid_job";
		}
	}
	
	/** 跳转到发布职位页面*/
	@GetMapping("user/enterprise/createjob")
	public String tocreatejob(Model model, HttpSession session){
		User user = (User) session.getAttribute("curr_user");
		if(user == null){
			return "redirect:/login";
		}
		EnterpriseUser euser = enterpriseUserService.getEnterpriseUserByUid(user.getId());
		List<Domain> domainList = companyService.showAllDomain();
		model.addAttribute("domainList", domainList);
		model.addAttribute("companyid", euser.getEnterprise_company_id());
		return "user/enterprise/createjob";
	}
	
	@PostMapping("user/enterprise/createjob")
	public String addJob(JobVo jobVo, HttpSession session, Model model){
		User user = (User) session.getAttribute("curr_user");
		Job job = jobVo.getJob();
		JobRequestDetail detail = jobVo.getJobDetail();
		Timestamp timestamp = new Timestamp(System.currentTimeMillis());
		job.setJob_creater_id(user.getId());
		job.setGmt_create(timestamp);
		job.setGmt_modified(timestamp);
		detail.setGmt_create(timestamp);
		detail.setGmt_modified(timestamp);
		boolean rs = jobService.addJob(jobVo);
		if(rs){
			return "redirect:/user/enterprise/myjob/1";
		}
		model.addAttribute("errormsg", "发布失败");
		return "user/enterprise/createjob";
	}
	
	
	@InitBinder("company")   
    public void initBinder1(WebDataBinder binder) {   
		binder.setFieldDefaultPrefix("company.");   
    } 
	@InitBinder("companyDetail")
	public void initBinder3(WebDataBinder binder){
		binder.setFieldDefaultPrefix("companyDetail."); 
	}
	@InitBinder("product")   
    public void initBinder2(WebDataBinder binder) {   
		binder.setFieldDefaultPrefix("product.");   
	}
}
